package com.hxwm.hwdbtool;

import com.hxwm.hwdbtool.controller.HwDBToolController;
import com.hxwm.hwdbtool.core.HwLogAppender;
import com.hxwm.hwdbtool.service.DataBaseNavService;
import com.hxwm.hwdbtool.util.HwUtil;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import org.apache.log4j.Logger;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;
import java.util.List;


public class HwDBToolMainApplication extends Application {
    private Logger logger = Logger.getLogger(HwDBToolMainApplication.class);
    private ConfigurableApplicationContext springContext;
    private Scene mainPane;

    private double xOffset = 0;
    private double yOffset = 0;

    @Override
    public void init() throws Exception {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(HwDBToolApplication.class);
        springContext = builder.run(getParameters().getRaw().toArray(new String[0]));
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        //数据初始化加载窗口
        Stage loadingScene = createLoadingScene();
        loadingScene.show();

        // 创建后台加载任务
        Task<Void> loadingTask = createLoadingTask();

        // 设置任务完成后的操作
        loadingTask.setOnSucceeded(event -> {
            // 加载完成后，切换到主界面
            loadingScene.close();
            primaryStage.setTitle("HwDBTool");
            primaryStage.setScene(mainPane);
            //添加图标
            Image appIconImage = new Image(getClass().getResourceAsStream("/static/icon/dbtoolbar/migration-app-icon.png"));
            primaryStage.getIcons().add(appIconImage);
            primaryStage.show();
        });

        // 启动任务
        new Thread(loadingTask).start();
    }

    @Override
    public void stop() throws Exception {
        springContext.close();
    }

    public static void main(String[] args) {
        System.setProperty("file-encoding", "UTF-8");
        launch();
    }

    /**
     * 初始化加载任务
     *
     * @return
     */
    private Task<Void> createLoadingTask() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                // 加载主页面
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main/hwdbtool.fxml"));
                mainPane = new Scene(fxmlLoader.load());

                // 获取主页面控制器中的页面元素
                HwDBToolController controller = fxmlLoader.getController();
                VBox controlLogVBox = controller.getControlLogVBox();//获取日志框VBox
                TreeView databaseNavTreeView = controller.getDatabaseNavTreeView();//获取数据库导航栏的TreeView
                TreeItem<String> virtualRoot = new TreeItem<>();// 创建一个虚拟根节点
                virtualRoot.setExpanded(true); // 展开虚拟根节点
                databaseNavTreeView.setRoot(virtualRoot);
                databaseNavTreeView.setShowRoot(false);

                //选择当前活动库表列表添加
                ComboBox dataBaseListComboBox = controller.getDataBaseListComboBox();
                dataBaseListComboBox.getItems().add("<N/A>");
                dataBaseListComboBox.setValue("<N/A>");

                DataBaseNavService dataBaseNavService = DataBaseNavService.getInstance();
                //加载用户配置文件
                List<TreeItem<String>> treeItems = dataBaseNavService.loadUserDatabaseInfoConfig();
                if(!HwUtil.isNullOrEmpty(treeItems)) {
                    //设置数据源map
                    controller.setHwConnectionListMap(dataBaseNavService.getHwConnectionListMap());
                    //添加数据源节点
                    for (TreeItem<String> treeItem : treeItems) {
                        virtualRoot.getChildren().add(treeItem);
                        dataBaseListComboBox.getItems().add(treeItem.getValue());
                    }
                }

                //创建单例 实现全局日志打印
                TableView tableView = HwLogAppender.tableView;
                controlLogVBox.getChildren().add(tableView);
                VBox.setVgrow(tableView, Priority.ALWAYS);//设置TableView在VBox中的垂直增长优先级为ALWAYS
                controller.getControlTabPane().getTabs().remove(0, 2);
                controller.getRightNavSplitPane().setDividerPositions(1.0);
                return null;
            }
        };
    }

    private static final double WIDTH = 300;
    private static final double HEIGHT = 300;
    private static final double RADIUS = 100;
    private static final double STROKE_WIDTH = 10;

    /**
     * 创建加载窗口
     *
     * @return
     */
    private Stage createLoadingScene() {
        // 创建一个自定义窗口，没有最大化、最小化和关闭按钮
        Stage loadingStage = new Stage();
//        Canvas canvas = new Canvas(WIDTH, HEIGHT);
//        GraphicsContext gc = canvas.getGraphicsContext2D();

//        Timeline timeline = new Timeline(new KeyFrame(Duration.millis(50), event -> {
//            double progress = (System.currentTimeMillis() % 10000) / 10000.0;
//            drawProgressBar(gc, progress);
//        }));
//        timeline.setCycleCount(Animation.INDEFINITE);
//        timeline.play();

        StackPane root = new StackPane();

        // 加载背景图像
        Image backgroundImage = new Image(getClass().getResourceAsStream("/static/image/migration-app-icon.png")); // 请替换为你的图像路径
        ImageView backgroundImageView = new ImageView(backgroundImage);
        //root.getChildren().addAll(backgroundImageView,canvas);
        root.getChildren().addAll(backgroundImageView);

        Scene scene = new Scene(root, backgroundImage.getWidth(), backgroundImage.getHeight());
        scene.setFill(null);
        loadingStage.initStyle(StageStyle.TRANSPARENT);
        loadingStage.setScene(scene);
        // 设置根布局的透明背景
        root.setStyle("-fx-background-color: transparent;");

        // 设置图像鼠标事件处理程序
        //用于记录鼠标按下时的偏移量。
        backgroundImageView.setOnMousePressed(event -> {
            xOffset = event.getSceneX();
            yOffset = event.getSceneY();
        });
        //用于更新窗口的位置，使其可以被拖动。
        backgroundImageView.setOnMouseDragged(event -> {
            loadingStage.setX(event.getScreenX() - xOffset);
            loadingStage.setY(event.getScreenY() - yOffset);
        });
        return loadingStage;
    }

    private void drawProgressBar(GraphicsContext gc, double progress) {
        gc.clearRect(0, 0, WIDTH, HEIGHT);

        double angle = 360 * progress;
        double centerX = WIDTH / 2;
        double centerY = HEIGHT / 2;

        // Draw background circle
        gc.setStroke(Color.LIGHTGRAY);
        gc.setLineWidth(STROKE_WIDTH);
        gc.strokeOval(centerX - RADIUS, centerY - RADIUS, RADIUS * 2, RADIUS * 2);

        // Draw progress arc
        gc.setStroke(Color.DODGERBLUE);
        gc.setLineWidth(STROKE_WIDTH);
        gc.strokeArc(centerX - RADIUS, centerY - RADIUS, RADIUS * 2, RADIUS * 2, 90, -angle, ArcType.OPEN);
    }
}